package com.example.job;


import lombok.extern.log4j.Log4j2;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Log4j2
public class BatchResult {

    /**
     * 线程执行
     *
     * @return
     */
    public String fun() throws InterruptedException {
        /**
         * 100w每次1w 只需要10次即可，但考虑到后续数据量的一个增长，我们这里还是设置了最大线程数为20，阻塞队列是10，这样做多可以容纳300w的数据，还超过的话会让当前线程直执行
         */
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 20, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10), new ThreadPoolExecutor.CallerRunsPolicy());
        final int pageSize = 10000;
        BaseResult tmpBaseResult = baseRequest(1, pageSize);
        if (tmpBaseResult.code != 200) {
            return "fail";
        }
        CountDownLatch countDownLatch = new CountDownLatch(tmpBaseResult.totalCount);
        for (int i = 1; i <= tmpBaseResult.totalCount; i++) {
            Integer page = new Integer(i);
            executor.execute(() -> {
                try {
                    BaseResult baseResult = baseRequest(page, pageSize);
                    if (tmpBaseResult.code == 200) {
                        try {
                            //执行业务逻辑
                        } catch (Exception e) {

                            log.error("数据处理异常:数据库异常:{}");
                        }
                    }
                } catch (Exception e) {
                    log.error("数据处理异常:多线程处理异常:{}", e);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }

        // 等待线程都执行完
        countDownLatch.await();

        log.info("执行成功");
        return "ok";
    }

    /**
     * 查询数据
     *
     * @param page
     * @param pageSize
     * @return
     */
    private BaseResult baseRequest(int page, int pageSize) {
        BaseResult baseResult = new BaseResult();
        return baseResult;
    }
    public class BaseResult {
        /**
         * 200 正常
         */
        private Integer code;

        /**
         * 总条数
         */
        private Integer totalCount;

        /**
         * 数据结果
         */
        private List<Object> lists;
    }
}

